<?php
namespace Home\Controller;

use Think\Controller;

//首页-控制器
class NurseController extends Controller {

    private $userModel;      //医院护士登录表
    private $BornNumModel;   //分娩量
    private $hospitalModel;  //医院

    public function __construct(){
        parent::__construct();
        //获取的model作为私有属性
        $this->userModel           = D('Nurse');                   //医院护士登录表
        $this->BornNumModel        = D('HospitalBornNumber');      //分娩量
        $this->HospitalModel       = D('Hospital');                //医院
    }

    /**
     * [startAndEndtime 根据时间参数，计算月初和月末两个时间]
     * @author xiezy
     * @date   2018-05-29
     * @param  [type]     $time [description]
     * @return [type]           [description]
     */
    private static function startAndEndtime($time){
        date_default_timezone_set('Asia/Shanghai');

        $y  =   date("Y",$time);
        $m  =   date("m",$time);
        $d  =   date("d",$time);
        $t  =   date('t',$time);                  // 本月一共有几天
        $t1 =   mktime(0,0,0,$m,1,$y);            // 创建本月开始时间
        $t2 =   mktime(23,59,59,$m,$t,$y);        // 创建本月结束时间

        return array('start_time'=>$t1,'end_time'=>$t2);
    }

    /**
     * [login 登录方法]
     * @author xiezy
     * @date   2018-05-24
     * @return [type]     [description]
     */
    public function login(){
        $where['user_name'] = I('post.username');
        $where['password'] = md5(I('post.password'));
        //根据用户名查询出一条数据
        $nurseData = $this->userModel->where($where)->find();
        if (!empty($nurseData)) {

            //获取护士当前登录的医院名字
            $where['id'] = $nurseData['hospital_id'];
            $hospitalName = $this->HospitalModel->where($where)->getField("hospital_name");

            cookie('login',true);                  // 缓存 当前登录医院账号
            cookie('hospitalName',$hospitalName);  // 缓存 当前操作医院
            cookie('nurseData',$nurseData);        // 缓存 当前护士数据

            $returndata['status'] = 1;
            $returndata['info']   = '登录成功';
            $returndata['url']    = U(MODULE_NAME.'/nurse/delivery_volume');
            $this->ajaxReturn($returndata);
        }else{
            cookie('login',false);
            $returndata['status'] = 0;
            $returndata['info']   = '登录失败';
            $this->ajaxReturn($returndata);
        }
    }

    /**
     * [delivery_volume 录入分娩量-页面]
     * @author xiezy
     * @date   2018-01-10
     * @return [type]     [description]
     */
    public function delivery_volume(){

        if ( !empty(cookie('nurseData')) ) {
            //1.获取登录数据，日期的起始、结束时间戳
            $nurseData            = cookie('nurseData');                                    //当前登录医院的护士数据
            $commitdate           = cookie('commitdate') ? cookie('commitdate') : time();
            $timeData             = static::startAndEndtime($commitdate);                   //提交日期的月初、月末时间戳

            //2.判断提交日期的当月日期范围是否存在？
            $where['nurse_id']    = $nurseData['id'];                                       //操作登录护士id
            $where['hospital_id'] = $nurseData['hospital_id'];                              //操作医院id
            $where['start_time']  = array("eq",$timeData['start_time']);
            $where['end_time']    = array("eq",$timeData['end_time']);
            $BornNumData          = $this->BornNumModel->where($where)->find();

            if (!empty($BornNumData['count_born_num'])) {
                //数据存在
                $BornNumData['count_born_num'] = unserialize($BornNumData['count_born_num']);

                $this->assign('born_num',$BornNumData['born_num']); //分娩量
                $this->assign('sale_num',$BornNumData['sale_num']); //销售量
                $this->assign('born_data',$BornNumData['count_born_num']);
            }
        }

        $this->display();
    }

    /**
     * [saveDeliveryOrder 保存医院的分娩量]
     * @author xiezy
     * @date   2018-05-24
     * @return [type]     [description]
     */
    public function saveDeliveryOrder(){
        //获取分娩量和对应的日期
        $data               = I('post.');                                   //页面提交数据（分娩日期，分娩数量）
        $nurseData          = cookie('nurseData');                          //当前登录医院的护士数据

        //1.获取日期的起始、结束时间戳
        $last_y             = date('Y',strtotime($data['del_date']));       //提交日期-月份
        $last_m             = date('m',strtotime($data['del_date']));       //提交日期-月份
        $now_y              = date("Y",time());                             //当月
        $now_m              = date("m",time());                             //当月
        $error_ym           = ($now_y * 12 + $now_m) - ($last_y * 12 + $last_m);
        if ( $error_ym >=2 ) {
            $returndata['status'] = 0;
            $returndata['info']   = '录入失败';
            $returndata['url']    = U(MODULE_NAME.'/nurse/delivery_volume');
            $this->ajaxReturn($returndata);
        }
        $del_date           = strtotime($data['del_date']);                 //转换为时间戳
                              cookie('commitdate',$del_date);               //记录提交日期的时间戳--便于展示【提交日期的分娩记录】
        $nowDate            = date('j',$del_date);                          //日期为几号
        $howDate            = date('t',$del_date);                          //当月有几天
        $timeData           = static::startAndEndtime($del_date);           //提交日期的月初、月末时间戳

        //2.判断提交日期的当月日期范围是否存在？
        $where['nurse_id']    = $nurseData['id'];                           //操作登录护士id
        $where['hospital_id'] = $nurseData['hospital_id'];                  //操作医院id
        $where['start_time']  = array("eq",$timeData['start_time']);
        $where['end_time']    = array("eq",$timeData['end_time']);
        $BornNumData = $this->BornNumModel->where($where)->find();

        if (!empty($BornNumData['count_born_num'])) {
            //数据存在
            $born_sum = 0;
            $sale_sum = 0;
            $BornNumData['count_born_num'] = unserialize($BornNumData['count_born_num']);
            foreach ($BornNumData['count_born_num'] as $key => $val) {
                if ($key == $nowDate){
                    $born_sum += $data['del_num'];
                    $sale_sum += $data['sale_num'];
                    $BornNumData['count_born_num'][$key] = array('date' => $data['del_date'],'num'=>$data['del_num'],'snum'=>$data['sale_num']);
                }else{
                    $born_sum += $BornNumData['count_born_num'][$key]['num'];
                    $sale_sum += $BornNumData['count_born_num'][$key]['snum'];
                }
            }
            $saveData['born_num']           = $born_sum;
            $saveData['sale_num']           = $sale_sum;
            $saveData['count_born_num']     = serialize($BornNumData['count_born_num']);

            $flag = $this->BornNumModel->where($where)->save($saveData);
        }else{
            //数据不存在,创建一个当月新的记录。
            $jsonData = array();

            for ($i=1; $i <= $howDate; $i++) {
                if ($i == $nowDate) {
                    $jsonData[$i]['date'] = $data['del_date']; //分娩日期 例：2018-5-20
                    $jsonData[$i]['num']  = $data['del_num'];  //分娩数量
                    $jsonData[$i]['snum'] = $data['sale_num']; //销售数量
                }else{
                    $jsonData[$i]['date'] = date("Y-m-",$del_date).$i; //分娩日期
                    $jsonData[$i]['num']  = 0;  //分娩数量
                    $jsonData[$i]['snum'] = 0;  //销售数量
                }
            }
            $newUserData['hospital_id']         = $nurseData['hospital_id'];//操作医院id
            $newUserData['nurse_id']            = $nurseData['id'];         //操作登录护士id
            $newUserData['born_num']            = $data['del_num'];         //当月分娩总量
            $newUserData['sale_num']            = $data['sale_num'];        //当月销售总量
            $newUserData['count_born_num']      = serialize($jsonData);     //存放当月记录，下标几号，一天一组array('日期','分娩量')
            $newUserData['start_time']          = $timeData['start_time'];  //当月开始时间戳
            $newUserData['end_time']            = $timeData['end_time'];    //当月结束时间戳

            $flag = $this->BornNumModel->add($newUserData);
        }

        //判断提示是否成功
        if ($flag) {
            $returndata['status'] = 1;
            $returndata['info']   = '录入成功';
        }else{
            $returndata['status'] = 0;
            $returndata['info']   = '录入失败';
        }

        $returndata['url']    = U(MODULE_NAME.'/nurse/delivery_volume');
        $this->ajaxReturn($returndata);
    }
}
